<template>
  <div class="subject-container">
    <div class="top-box">
      <span class="subject-num">{{$parent.activeSubjectIndex + 1}}</span>
      <span class="subject-all">/{{subject.length}}</span>
      <span class="timer">耗时：{{formatSecond2Minute}}</span>
    </div>
    <!-- 题目box -->
    <div v-for="(item,index) of subject" v-show="$parent.activeSubjectIndex === index" :key="item.subject_id"
         class="subject-box">
      <subject-title
        :subtitle="item.subtitles_en_url"
        :file-url="item.file_url"
        :display-type="parseInt(item.display_type)"
        :txt="item.subject_content"></subject-title>
      <div v-if="parseInt(item.subject_type) === 13">
        <subject-item4-type13
          v-on="$listeners"
          v-for="(subjectItem, subjectItemIndex) of item.itemList" :key="subjectItem.subject_item_id"
          :subject-index="index"
          :subject-item-index="subjectItemIndex"
          :stu-answer="item.answerList"></subject-item4-type13>
      </div>
      <div v-else>
        <subject-item
          v-on="$listeners"
          v-for="subjectItem of item.itemList" :key="subjectItem.subject_item_id"
          :code="subjectItem.answer_code"
          :txt="subjectItem.resource_subject_item_tent"
          :display-type="parseInt(subjectItem.item_type)"
          :file-url="subjectItem.file_url"
          :sl-code="item.slCode"
          :subject-index="index"
          :subject-type="parseInt(item.subject_type)"
          :subtitle="subjectItem.subtitles_en_url"></subject-item>
      </div>
    </div>
    <div class="submit-box">
      <div>
        <el-button @click="changeSubject(-1)"
                   :disabled="$parent.activeSubjectIndex === 0">上一题
        </el-button>
        <el-button @click="changeSubject(0)"
                   :disabled="$parent.activeSubjectIndex === subject.length - 1">下一题
        </el-button>
      </div>
      <el-button type="primary" @click="submitSubjectCheck">提交</el-button>
    </div>
  </div>
</template>

<script>
import subjectItem from './subjectItem'
import { pushAnswerTime, submitSubject } from '@/api/student/training/multiple'
import subjectTitle from './subjectTitle'
import subjectItem4Type13 from './subjectItem4Type13'

export default {
  name: 'subjectPanel',
  props: {
    subject: Array,
    stuNodeCaseId: String,
    stuTaskCaseId: String
  },
  data () {
    return {
      interValFlag: null,
      timer: 0,
      score: 0
    }
  },
  methods: {
    changeSubject (flag) {
      if (flag === -1 && this.$parent.activeSubjectIndex === 0) return
      if (flag === 0 && this.$parent.activeSubjectIndex === this.subject.length - 1) return
      if (flag === -1) this.$emit('changeIndex', this.$parent.activeSubjectIndex - 1)
      else this.$emit('changeIndex', this.$parent.activeSubjectIndex + 1)
    },
    countDown () {
      this.interValFlag = setInterval(() => {
        this.timer++
        if (this.timer % 8 === 0 && this.timer !== 0) this.pushServerTime()
        if (this.timer >= 3600) {
          clearInterval(this.interValFlag)
          this.$alert('由于长时间未作答，题目失效，请刷新页面', '提示', {
            confirmButtonText: '确定',
            callback: () => location.reload()
          })
        }
      }, 1000)
    },
    async pushServerTime () {
      try {
        await pushAnswerTime({
          stuMTaskCaseId: this.$parent.stuTaskCaseId
        })
      } catch (e) {
        clearInterval(this.interValFlag)
      }
    },
    submitSubjectCheck () {
      let allFinished = true
      for (let i = 0; i < this.subject.length; i++) {
        if (!this.subject[i].slCode) {
          allFinished = false
          break
        }
      }
      this.$alert(allFinished ? '确定提交吗？' : '存在未作答的题目，确定提交吗？', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') {
            let json = this.getStuAnswer()
            this.toSubmitSubject(json)
            this.$router.push({ name: 'taskFinished' })
          }
        }
      })
    },
    async toSubmitSubject (resultJson) {
      await submitSubject({
        score: this.score,
        stuMNodeCaseId: this.stuNodeCaseId,
        stuMTaskCaseId: this.stuTaskCaseId,
        resultJson
      })
    },
    getStuAnswer (subject) {
      const handlerMap = new Map()
      handlerMap.set(10, 'handlerSubjectType10')
      handlerMap.set(11, 'handlerSubjectType11')
      handlerMap.set(12, 'handlerSubjectType12')
      handlerMap.set(13, 'handlerSubjectType13')
      const handlerMethod = this[handlerMap.get(this._.toInteger(subject.subject_type))]
      if (!handlerMethod) throw new Error('subject type is not handler method')
      return handlerMethod()
    },
    /**
     * 单选
     */
    handlerSubjectType10 (subject) {
      let subjectItemId = null
      const subjectItemArray = subject.itemList
      for (let i = 0; i < subjectItemArray.length; i++) {
        if (subjectItemArray[i].answer_code === subject.slCode) {
          subjectItemId = subjectItemArray[i].subject_item_id
          break
        }
      }

      const resultJson = {
        subject_type: 10,
        score: this._.isEmpty(subject.score) ? 0 : subject.score,
        right_flag: this._.isEmpty(subject.right_flag) ? 0 : 1,
        sort_index: subject.sort_index,
        stu_answer: subject.slCode,
        subject_id: subject.subject_id,
        right_answer: subject.right_answer,
        subject_item_id: subjectItemId
      }
      return resultJson
    },
    /**
     * 多选
     */
    handlerSubjectType11 (subject) {
      let subjectItemIds = []
      const subjectItemArray = subject.itemList
      for (let i = 0; i < subjectItemArray.length; i++) {
        const answerCode = subjectItemArray[i].answer_code
        const stuslCodeArray = subject.slCode.split(',')
        if (stuslCodeArray.includes(answerCode)) {
          subjectItemIds.push(subjectItemArray[i].subject_item_id)
        }
      }

      const resultJson = {
        subject_type: 11,
        score: this._.isEmpty(subject.score) ? 0 : subject.score,
        right_flag: this._.isEmpty(subject.right_flag) ? 0 : 1,
        sort_index: subject.sort_index,
        stu_answer: subject.slCode,
        subject_id: subject.subject_id,
        right_answer: subject.right_answer,
        subject_item_id: subjectItemIds.join(',')
      }
      return resultJson
    },
    /**
     * 判断
     */
    handlerSubjectType12 (subject) {
      let subjectItemId = null
      const subjectItemArray = subject.itemList

      for (let i = 0; i < subjectItemArray.length; i++) {
        if (subjectItemArray[i].resource_subject_item_tent === subject.slCode) {
          subjectItemId = subjectItemArray[i].subject_item_id
          break
        }
      }

      const resultJson = {
        subject_type: 12,
        score: this._.isEmpty(subject.score) ? 0 : subject.score,
        right_flag: this._.isEmpty(subject.right_flag) ? 0 : 1,
        sort_index: subject.sort_index,
        stu_answer: subject.slCode,
        subject_id: subject.subject_id,
        right_answer: subject.resource_subject_item_tent,
        subject_item_id: subjectItemId
      }
      return resultJson
    },
    /**
     * 填空题
     */
    handlerSubjectType13 (subject) {
      const answerList = subject.answerList

      const resultJson = {
        subject_type: 13,
        score: this._.isEmpty(subject.score) ? 0 : subject.score,
        right_flag: this._.isEmpty(subject.right_flag) ? 0 : 1,
        sort_index: subject.sort_index,
        subject_id: subject.subject_id,
        right_answer: answerList || []
      }
      return resultJson
    }
  },
  computed: {
    formatSecond2Minute () {
      const minite = parseInt(this.timer / 60)
      let second = this.timer - minite * 60
      if (second < 10) second = '0' + second
      return [minite, second].join(':')
    }
  },
  destroyed () {
    clearInterval(this.interValFlag)
  },
  created () {
    this.countDown()
  },
  components: {
    subjectItem, subjectTitle, subjectItem4Type13
  }
}
</script>

<style scoped lang="scss">
  .subject-container {
    width: 728px;
    height: 728px;
    border: 1px solid #e5e5e5;
    background-color: white;
    box-sizing: border-box;
    padding: 22px;

    .top-box {
      width: 100%;
      display: flex;
      height: 40px;
      align-items: center;

      .subject-num {
        font-size: 26px;
        font-family: PingFang SC;
        font-weight: 500;
        color: rgba(248, 111, 51, 1);
      }

      .subject-all {
        font-size: 20px;
        font-family: PingFang SC;
        font-weight: 500;
        color: rgba(248, 111, 51, 1);
      }

      .timer {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: rgba(16, 29, 55, 1);
        margin-left: 32px;
      }
    }

    .subject-box {
      margin-top: 30px;
      height: 540px;
      overflow-y: auto;
      width: 100%;
    }

    .submit-box {
      width: 100%;
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
</style>
